package concurrecy;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

class Fibonacci implements Callable<Integer> {
    private int n;

    private int fib(int n) {
        if(n == 0 || n == 1)
            return 1;
        return fib(n - 1) + fib(n - 2);
    }

    public Fibonacci(int n) {
        this.n = n;
    }

    @Override
    public Integer call() throws Exception {
        return fib(n);
    }
}

public class FibonacciDemo {
    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        Random random = new Random();
        List<Future<Integer>> rs = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            rs.add(service.submit(new Fibonacci(random.nextInt(20))));
        }
        while(rs.size() > 0) {
            Iterator<Future<Integer>> iterator = rs.iterator();
            while(iterator.hasNext()) {
                try {
                    Integer integer = iterator.next().get(10, TimeUnit.MILLISECONDS);
                    iterator.remove();
                    System.out.println(integer);
                } catch (Exception e) {
                    continue;
                }
            }
        }
        service.shutdown();
    }
}
